package com.xpsoft.oa.service.project.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.reflect.TypeToken;
import com.xpsoft.core.service.impl.BaseServiceImpl;
import com.xpsoft.core.util.ContextUtil;
import com.xpsoft.core.util.JsonUtil;
import com.xpsoft.oa.dao.project.ProjectDesignRegDao;
import com.xpsoft.oa.dao.project.ProjectDesignRegInfoDao;
import com.xpsoft.oa.model.project.ProjectDesignReg;
import com.xpsoft.oa.model.project.ProjectDesignRegInfo;
import com.xpsoft.oa.model.project.ProjectSignRegInfo;
import com.xpsoft.oa.service.project.ProjectDesignRegService;

public class ProjectDesignRegServiceImpl extends BaseServiceImpl<ProjectDesignReg> implements ProjectDesignRegService{
	private ProjectDesignRegDao dao;
	@Autowired
	private ProjectDesignRegInfoDao projectDesignRegInfoDao;
	public ProjectDesignRegServiceImpl(ProjectDesignRegDao dao) {
		super(dao);
		this.dao=dao;
	}

	@Override
	public void saveProjectDesignReg(ProjectDesignReg projectDesignReg,
			String regInfoDataList) {
		// TODO Auto-generated method stub
		Boolean isNew = true;//新增标志
		if(projectDesignReg.getId()!=null){
			isNew = false;
		}else{
			projectDesignReg.setCreatetime(new Date());
			projectDesignReg.setCreateUser(ContextUtil.getCurrentUser());
		}
		dao.save(projectDesignReg);
		if(StringUtils.isNotBlank(regInfoDataList)){
			List<ProjectDesignRegInfo> projectDesignRegInfoList = JsonUtil.fromJsonTypes(regInfoDataList,
					new TypeToken<List<ProjectDesignRegInfo>>() {
					}.getType());
			if(!isNew){//修改
				List<Long> idList = new ArrayList<Long>();
				for(ProjectDesignRegInfo projectDesignRegInfo:projectDesignRegInfoList){
					if(projectDesignRegInfo.getId()!=null){//修改的记录
						idList.add(projectDesignRegInfo.getId());
					}
				}
				if(idList.size()>0){//先进行删除
					projectDesignRegInfoDao.deleteProjectDesignRegInfos(projectDesignReg.getId(), idList);
				}
			}
			for(ProjectDesignRegInfo projectDesignRegInfo:projectDesignRegInfoList){
				projectDesignRegInfo.setProjectDesignReg(projectDesignReg);
				projectDesignRegInfoDao.save(projectDesignRegInfo);
			}
		}
	}

}